package com.beimi.web.handler.api;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.beimi.cache.UserCacheService;
import com.beimi.common.ResultData;
import com.beimi.core.BMDataContext;
import com.beimi.dao.jpa.TokenRepository;
import com.beimi.dao.model.PlayUser;
import com.beimi.dao.model.PlayUserClient;
import com.beimi.dao.model.Token;
import com.beimi.game.conf.GameAccountConfig;
import com.beimi.util.Base62;
import com.beimi.util.BrowserClient;
import com.beimi.util.MessageEnum;
import com.beimi.util.RandomKey;
import com.beimi.util.UKTools;
import com.beimi.util.UUIDUtils;
import com.beimi.web.handler.Handler;

@RestController
@RequestMapping("/api/guest")
public class GuestRegisterController extends Handler {

	@Autowired
	private TokenRepository tokenRepository;

	@Autowired
	private UserCacheService userCacheService;

	@Autowired
	GameAccountConfig config;

	@RequestMapping
	public ResponseEntity<ResultData> guest(HttpServletRequest request, @Valid String token) {
		PlayUserClient playUserClient = null;
		Token userToken = null;
		if (!StringUtils.isBlank(token)) {
			userToken = tokenRepository.findById(token);
			if (userToken != null && userToken.getExptime() != null && userToken.getExptime().after(new Date())) {
				// 返回token， 并返回游客数据给游客
				playUserClient = userCacheService.findOne(userToken.getUserid());
				if (playUserClient != null) {
					playUserClient.setToken(userToken.getId());
				}
			} else {
				if (userToken != null) {
					tokenRepository.delete(userToken);
					userToken = null;
				}
			}
		}

		if (playUserClient == null) {
			try {
				playUserClient = register(new PlayUser(), request);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (userToken == null) {
			userToken = new Token();
			userToken.setId(UUIDUtils.getUUID());
			userToken.setUserid(playUserClient.getId());
			userToken.setCreatetime(new Date());
			userToken.setOrgi(playUserClient.getOrgi());
			if (config != null && config.getExpdays() > 0) {
				userToken.setExptime(new Date(System.currentTimeMillis() + 60 * 60 * 24 * config.getExpdays() * 1000));// 默认有效期
			} else {
				userToken.setExptime(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 7 * 1000));// 默认有效期
			}
			userToken.setLastlogintime(new Date());
			userToken.setUpdatetime(new Date(0));

			tokenRepository.save(userToken);
		}
		playUserClient.setToken(userToken.getId());

		userCacheService.save(playUserClient);
		return new ResponseEntity<>(new ResultData(playUserClient != null,
				playUserClient != null ? MessageEnum.USER_REGISTER_SUCCESS : MessageEnum.USER_REGISTER_FAILD_USERNAME,
				playUserClient, userToken), HttpStatus.OK);
	}

	/**
	 * 注册用户
	 * 
	 * @param player
	 * @return
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public PlayUserClient register(PlayUser player, HttpServletRequest request)
			throws IllegalAccessException, InvocationTargetException {
		PlayUserClient playUserClient = create(player, request);
		return playUserClient;
	}

	private PlayUserClient create(PlayUser player, HttpServletRequest request) {
		PlayUserClient playUserClient = null;
		if (player != null) {
			if (StringUtils.isBlank(player.getUsername())) {
				player.setUsername("Guest_" + Base62.encode(UUIDUtils.getUUID().toLowerCase()));
			}
			if (!StringUtils.isBlank(player.getPassword())) {
				player.setPassword(player.getPassword());
			} else {
				player.setPassword(RandomKey.genRandomNum(6));// 随机生成一个6位数的密码
																// ，备用
			}
			// player.setPlayertype(0); //玩家类型
			player.setId(System.currentTimeMillis());
			player.setCreatetime(new Date());
			player.setUpdatetime(new Date());
			player.setLastlogintime(new Date());

			BrowserClient client = UKTools.parseClient(request);
			player.setOstype(client.getOs());
			player.setBrowser(client.getBrowser());
			if (request != null) {
				String usetAgent = request.getHeader("User-Agent");
				if (!StringUtils.isBlank(usetAgent)) {
					if (usetAgent.length() > 255) {
						player.setUseragent(usetAgent.substring(0, 250));
					} else {
						player.setUseragent(usetAgent);
					}
				}
			}

			player.setOrgi(BMDataContext.SYSTEM_ORGI);

			if (config != null) {
				player.setGoldcoins(config.getInitcoins());
				player.setCards(config.getInitcards());
				player.setDiamonds(config.getInitdiamonds());
			}

			playUserClient = new PlayUserClient();
			try {
				BeanUtils.copyProperties(playUserClient, player);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return playUserClient;
	}

}
